package com.jy.rhin.support.util;

import com.jy.rhin.infra.exception.RhinAggrErrorType;
import com.jy.rhin.infra.exception.RhinAggrException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Objects;

/**
 * @author WeiQ
 * @date 2022/7/7 11:03
 * 断言工具类
 */
public class Asserts {

    /**
     * 验证对象非空
     *
     * @param obj
     * @param errorType
     * @return
     */
    public static void nonNull(Object obj, RhinAggrErrorType errorType, String... msg) {
        isTrue(Objects.nonNull(obj), errorType, msg);
    }

    /**
     * 验证对象为空
     *
     * @param obj
     * @param errorType
     * @return
     */
    public static void isNull(Object obj, RhinAggrErrorType errorType, String... msg) {
        isTrue(Objects.isNull(obj), errorType, msg);
    }

    /**
     * 验证字符串非空
     *
     * @param str
     * @param errorType
     */
    public static void notEmpty(CharSequence str, RhinAggrErrorType errorType, String... msg) {
        isTrue(!StringUtils.isEmpty(str), errorType, msg);
    }

    /**
     * 验证集合非空
     *
     * @param list
     * @param errorType
     * @return
     */
    public static void notEmpty(Collection<?> list, RhinAggrErrorType errorType, String... msg) {
        isFalse(CollectionUtils.isEmpty(list), errorType, msg);
    }

    public static void equals(Object source, Object target, RhinAggrErrorType errorType, String... msg) {
        isTrue(Objects.equals(source, target), errorType, msg);
    }

    public static void lt(Comparable source, Comparable target, RhinAggrErrorType errorType, String... msg) {
        nonNull(source, errorType, msg);
        nonNull(target, errorType, msg);
        isTrue(source.compareTo(target) < 0, errorType, msg);
    }

    public static void gt(Comparable source, Comparable target, RhinAggrErrorType errorType, String... msg) {
        lt(target, source, errorType, msg);
    }

    public static void isTrue(Boolean flag, RhinAggrErrorType errorType, String... msg) {
        if (!Boolean.TRUE.equals(flag)) {
            throw new RhinAggrException(errorType, msg == null || msg.length ==0 ? "" : msg[0]);
        }
    }

    public static void isFalse(Boolean flag, RhinAggrErrorType errorType, String... msg) {
        if (!Boolean.FALSE.equals(flag)) {
            throw new RhinAggrException(errorType, msg == null || msg.length ==0 ? "" : msg[0]);
        }
    }

    private Asserts() {
    }
}
